<?php
// 应用公共文件


use think\facade\Db;
use think\facade\Request;

if (!function_exists('completeUrl')) {
    function completeUrl($url)
    {
        if (empty($url)) {
            return $url;
        }

        if (strpos($url, 'http') !== false) {
            return $url;
        }
        if (!empty($str) && substr($str, 0, 1) === '/') {

        } else {
            $url = '/' . $url;
        }

        $pageURL = 'http';
        if (isset($_SERVER['HTTPS']) && $_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";

        $pageURL .= $_SERVER["SERVER_NAME"];

        return $pageURL . $url;
    }
}

if (!function_exists('getUserInfo')) {
    function getUserInfo()
    {
        $token = Request::header('Authorization');
        if (empty($token)) {
            return [];
        }

        // 去掉 Bearer 前缀
        $token = str_replace('Bearer ', '', $token);

        // 从tokens表查询token信息
        $tokenInfo = Db::name('user_tokens')
            ->where('token', $token)
            ->where('status', 1)
            ->find();

        $user = false;
        if (!empty($tokenInfo)) {
            // 根据user_id查询用户基本信息
            $user = Db::name('user')
                ->where('id', $tokenInfo['user_id'])
                ->where('status', 1)
                ->find();
            return $user;
        }

        return $user;
    }
}

if (!function_exists('dataPermissionCheck')) {
    function dataPermissionCheck($user)
    {
        if (!empty($user)) {
            if (in_array($user['id'],[1])) {
                return 'admin';
            } else if ($user['company_admin'] == 200) {
                return 'company';
            } else {
                return 'user';
            }
        }
    }
}